# -*- coding utf-8 -*-
__plugin__ = "Hdin.tv"
__author__ = "vas3k"
__date__ ="31.01.2010"
__version__ = "0.5"

import sys, os
import xbmcplugin
import xbmcgui
import xbmc
from hdin import Hdin

def listSerials():
    serials = myHdin.getSerials()

    for serial in serials:
        url = sys.argv[0] + "?mode=1&serial=" + serial["namelink"]
        listitem = xbmcgui.ListItem(serial["name"])
        listitem.setIconImage(serial["image"])
        xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=True)
    return

def listSeasons(serial="HouseMD"):
    seasons = myHdin.getSerialSeasons(serial)

    for season in seasons:
        url = sys.argv[0] + "?mode=2&serial=" + serial + "&season=" + season
        listitem = xbmcgui.ListItem("Сезон %i" % int(season))
        xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=True)
    return

def listEpisodes(serial="HouseMD", season="01"):
    episodes = myHdin.getSeasonEpisodes(serial, season)

    for episode in episodes:
        url = sys.argv[0] + "?mode=3&serial=" + serial + "&season=" + season + "&episode=" + episode["episode"]
        listitem = xbmcgui.ListItem("%sx%s - %s" % (season, episode["episode"], episode["title"][4:]), episode["name"])
        listitem.setIconImage(episode["image"])
        xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=False)
    return

def playEpisode(serial="HouseMD", seasonN="01", episodeN="01"):
    episode = myHdin.getEpisode(serial, seasonN, episodeN)

    listitem = xbmcgui.ListItem("%sx%s - %s" % (seasonN, episodeN, episode["name"]))
    listitem.setThumbnailImage(episode["image"])
    xbmc.Player(xbmc.PLAYER_CORE_MPLAYER).play(episode["video"], listitem, True)

def getParams():
    param=[]
    paramstring=sys.argv[2]
    if len(paramstring)>=2:
        params=sys.argv[2]
        cleanedparams=params.replace('?','')
        if (params[len(params)-1]=='/'):
            params=params[0:len(params)-2]
        pairsofparams=cleanedparams.split('&')
        param={}
        for i in range(len(pairsofparams)):
            splitparams={}
            splitparams=pairsofparams[i].split('=')
            if (len(splitparams))==2:
                param[splitparams[0]]=splitparams[1]

    return param

def saveAuth(username, password):
    filename = os.path.join(os.path.dirname(__file__), "settings.txt").replace("\\", "/")
    xbmc.log("SAVE: " + filename)
    file = open(filename, "w")
    file.write(str(username) + "\n")
    file.write(str(password) + "\n")
    file.close()

def loadAuth():
    filename = os.path.join(os.path.dirname(__file__), "settings.txt").replace("\\", "/")
    xbmc.log("LOAD: " + filename)
    file = open(filename, "r")
    u = file.readline()
    p = file.readline()
    file.close()
    return u, p

def showAuth():
    user_keyboard = xbmc.Keyboard('user')
    user_keyboard.setHeading('Enter username')
    user_keyboard.doModal()
    if (user_keyboard.isConfirmed()):
        username = user_keyboard.getText()

    pass_keyboard = xbmc.Keyboard('password')
    pass_keyboard.setHeading('Enter password')
    pass_keyboard.setHiddenInput(True)
    pass_keyboard.doModal()
    if (pass_keyboard.isConfirmed()):
        password = pass_keyboard.getText()
        saveAuth(username, password)

myHdin = None

try:
    USER, PASS = loadAuth()
    myHdin = Hdin(user=USER, password=PASS)
except:
    showAuth()
    try:
        USER, PASS = loadAuth()
        myHdin = Hdin(user=USER, password=PASS)
    except:
        dialog = xbmcgui.Dialog()
        ok = dialog.ok('Не правильно :P', 'Проверьте логин и пароль')
        raise Exception("Unauthorized")

params = getParams()
mode = None
serial = None
season = None
episode = None

try:
    mode = int(params["mode"])
except:
    pass

try:
    serial = params["serial"]
except:
    pass

try:
    season = params["season"]
except:
    pass

try:
    episode = params["episode"]
except:
    pass

if mode == None or mode < 1:
    listSerials()
    xbmcplugin.endOfDirectory(int(sys.argv[1]), updateListing=False, cacheToDisc=True)
elif mode == 1:
    listSeasons(serial)
    xbmcplugin.endOfDirectory(int(sys.argv[1]), updateListing=False, cacheToDisc=True)
elif mode == 2:
    listEpisodes(serial, season)
    xbmcplugin.endOfDirectory(int(sys.argv[1]), updateListing=False, cacheToDisc=True)
elif mode == 3:
    playEpisode(serial, season, episode)

